#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
# @version: v1.0
# @author : wlis
# @Email : 1259319710@qq.com
# @Project : g-carbon-bio
# @File : csv_help.py
# @Software: PyCharm
# @time: 2025/2/4 16:05
# @description :  处理CSV 文件读取过程
"""
import pandas as pd
import os


class CSVHelp:
    def __init__(self, folder_name='service/data'):
        """
        初始化 CSVHelp 类

        Args:
            folder_name (str): 存放 CSV 文件的文件夹名称，默认为 'service/data'
        """
        # 指定目标目录
        self.target_directory_name = 'g-carbon-bio'
        found_directory = self.find_parent_directory()

        if found_directory:
            self.folder_path = os.path.join(found_directory, folder_name)
            # 如果文件夹不存在，则创建它
            if not os.path.exists(self.folder_path):
                os.makedirs(self.folder_path)
                print(f"Folder '{self.folder_path}' created.")
            else:
                print(f"Folder '{self.folder_path}' already exists.")
        else:
            print(f"Target directory '{self.target_directory_name}' not found.")

    def find_parent_directory(self, start_directory=None):
        """
        从指定的目录开始，向上查找直到找到目标目录。

        :return: 找到的目标目录的路径，如果未找到则返回 None
        """
        # 如果没有指定开始查找的目录，则使用当前工作目录
        if start_directory is None:
            start_directory = os.getcwd()

        current_directory = start_directory

        while current_directory:
            # 获取当前目录的最后部分
            current_name = os.path.basename(current_directory)

            # 检查是否为目标目录
            if current_name == self.target_directory_name:
                return current_directory

            # 获取上一级目录
            current_directory = os.path.dirname(current_directory)

        return None

    def read_csv(self, file_name):
        """
        从指定文件名的 CSV 文件读取数据

        Args:
            file_name (str): CSV 文件名

        Returns:
            DataFrame: 读取的数据
        """
        try:
            file_path = os.path.join(self.folder_path, file_name)
            df = pd.read_csv(file_path)
            return df
        except FileNotFoundError:
            print(f"File {file_path} not found.")
            return None
        except Exception as e:
            print(f"Error reading the CSV file: {e}")
            return None

    def write_to_csv(self, data, file_name):
        """
        将数据写入到指定文件名的 CSV 文件

        Args:
            data (DataFrame): 要写入的数据
            file_name (str): CSV 文件名
        """
        try:
            file_path = os.path.join(self.folder_path, file_name)
            data.to_csv(file_path, index=False)
            print(f"Data written to {file_path} successfully.")
        except Exception as e:
            print(f"Error writing to the CSV file: {e}")

# # 示例用法
# if __name__ == "__main__":
#     # 创建 CSVHelp 实例
#     csv_helper = CSVHelp()
#
#     # 创建一个示例 DataFrame
#     new_data = {
#         'Name': ['Alice', 'Bob', 'Charlie'],
#         'Age': [25, 30, 35],
#         'City': ['New York', 'Los Angeles', 'Chicago']
#     }
#     new_df = pd.DataFrame(new_data)
#
#     # 写入到新的 CSV 文件
#     output_file_name = 'output_data.csv'  # 输出文件名
#     csv_helper.write_to_csv(new_df, output_file_name)
#
#     # 读取 CSV 文件
#     read_data = csv_helper.read_csv(output_file_name)
#     if read_data is not None:
#         print("Data read from CSV:")
#         print(read_data)
